<template>
    <el-dialog v-model="show" title="客户福利采购对账" width="20%" align-center @close="handleClose">
        <el-row>
            <el-col class="flex" :span="24">
                <div class="label">
                    对账/开票日期：
                </div>
                <el-date-picker v-model="reconciliationDate" type="date" placeholder="年-月-日" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    产品名称：

                </div>
                <div>{{ props.initList.welfareName }}</div>
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    入库数量：
                </div>
                <div>{{ props.initList.purchaseNumber }}</div>
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    总价：
                </div>
                <div>{{ Number(props.initList.price) * Number(props.initList.purchaseNumber) }}</div>
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    实际金额：
                </div>
                <el-input v-model="reconciliationAmount" placeholder="请输入实际金额" />
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    备注：
                </div>
                <el-input v-model="reconciliationRemark" placeholder="请输入备注" />
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit()">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { welfareReconciliationApi } from '@/api/sj/purchaseManagement/welfareProcurement/index'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);
const reconciliationAmount = ref();
const reconciliationDate = ref('');
const reconciliationRemark = ref('');

watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
        reconciliationDate.value = getCurrentDateFormatted()
    }
}, { deep: true });

const handleSubmit = async () => {
    // 检查并处理空值或无效值
    if (!props.initList.price || !props.initList.purchaseNumber) {
        return proxy?.$modal.msgError('请检查订单价格和数量');
    }

    const price = parseFloat(props.initList.price) * parseFloat(props.initList.purchaseNumber);

    // 检查必填项
    if (!reconciliationDate.value) return proxy?.$modal.msgError('请选择对账/开票日期');
    if (!reconciliationAmount.value) return proxy?.$modal.msgError('请输入实际金额');
    // if (!reconciliationRemark.value) return proxy?.$modal.msgError('请输入备注');

    const amount = parseFloat(reconciliationAmount.value);

    if (isNaN(price) || isNaN(amount)) {
        return proxy?.$modal.msgError('输入的金额格式不正确');
    }

    if (price === amount) {
        try {
            await submit();
        } catch (error) {
            console.error('提交失败:', error);
            proxy?.$modal.msgError('提交失败，请稍后再试');
        }
        return;
    }

    const priceDifference = price - amount;

    // 提示信息优化
    const message = `实际对账金额与订单总金额不一致，${priceDifference > 0 ? '少了' + priceDifference.toFixed(2) + '元' : '多了' + Math.abs(priceDifference).toFixed(2) + '元'}，您确定保存吗？`;

    ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            try {
                await submit();
            } catch (error) {
                console.error('提交失败:', error);
                proxy?.$modal.msgError('提交失败，请稍后再试');
            }
        })
        .catch(() => { });
};

/** 获取当前日期 */
const getCurrentDateFormatted = () => {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
    const day = String(today.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}

const submit = async () => {
    try {
        const { code } = await welfareReconciliationApi({
            welfareId: props.initList.welfareId,
            welfareApplyId: props.initList.id,
            reconciliationDate: reconciliationDate.value,
            reconciliationAmount: reconciliationAmount.value,
            reconciliationRemark: reconciliationRemark.value
        })

        if (code === 200) {
            proxy?.$modal.msgSuccess('操作成功');
            emits('submit', true);
            handleClose();
        }
    } catch (error) {

    }
};


const handleClose = () => {
    emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.label {
    height: 32px;
    line-height: 32px;
    font-weight: 700;
    display: inline-flex;
    justify-content: flex-end;
    align-items: flex-start;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    flex: 0 0 auto;
    font-size: var(--el-form-label-font-size);
    color: var(--el-text-color-regular);
    width: 130px;
}

.flex {
    display: flex;
    align-items: center;
}

.el-col {
    margin-bottom: 10px;
}
</style>